<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-page-header :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
      <el-container style="margin-top: 3vh">
        <el-header>
          <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
            <el-menu-item index="0">日消费汇总</el-menu-item>
            <el-menu-item index="1">坐席日消费</el-menu-item>
          </el-menu>
        </el-header>
        <el-main id="showMain" style="height: 71vh">
          <div v-show="isShows[0].isShow">
                <div ref="histogram" id="histogram">
                </div>
                <div class="advanced-box-shadow"   >
                  <el-table
                      :data="tableData"
                      border
                      show-summary
                      style="width: 100%">
                    <el-table-column
                        prop="id"
                        label="日期"
                        style="width: 50%"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="amount3"
                        sortable
                        label="消费金额(元)">
                    </el-table-column>
                  </el-table>
                </div>
              <div style="height: 5vh">

              </div>
          </div>
          <div v-show="isShows[1].isShow" style="background-color: #fff;padding: 2vh 0">
            <el-card>
              <el-form :inline="true" ref="form" :model="queryMap"  size="small" style="margin-top: 2vh">

                <div class="block" style="margin-bottom: 1vh">
                  <span class="demonstration" style="color: #1f2d3d;">呼叫时间: </span>
                  <el-date-picker
                      v-model="value2"
                      type="daterange"
                      align="right"
                      unlink-panels
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="height: 34px;"
                      :picker-options="pickerOptions">
                  </el-date-picker>
                  <el-form-item >
                    <el-select v-model="userId" style="width: 140px;" filterable placeholder="请选择坐席昵称">
                      <el-option
                          v-for="(user) in userList"
                          :key="user.userId"
                          :label="user.userName+'('+user.nickName+')'"
                          :value="user.userId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-select v-model="accountName" style="width: 140px;" filterable placeholder="请选择账号" @change="getSeatsConsumeLogChange()">
                      <el-option
                          v-for="(item,index) in accounts"
                          :key="index"
                          :label="item"
                          :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item >
                    <el-button style="margin-left: 2vh;"  icon="el-icon-refresh" @click="reset()">重置</el-button>
                    <el-button type="primary"  icon="el-icon-search" @click="getSeatsConsumeLog()">查询</el-button>
                  </el-form-item>
                </div>
              </el-form>
              <!-- 表格区域 -->
              <el-table ref="multipleTable" size="small"
                        border style="width: 100%;" height="420"
                        :data="tableData2"
              >
                <el-table-column prop="endTime" label="消费日期" width="300"></el-table-column>
                <el-table-column prop="userName" label="坐席名称" width="300"></el-table-column>
                <el-table-column prop="accountName" label="账户" width="300"></el-table-column>
                <el-table-column prop="consumptionAmount" label="消费金额(元)" width="328"></el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-card>
  </div>
</template>

<script>

export default {
  data() {
    return {
      value2: '',//日期选择器
      userId:'',
      userList:'',
      accounts:[],
      accountName:'',
      tableData2:[],
      tableData: [{
        id: new Date(),
        amount3: 10
      }, {
        id: new Date(),
        amount3: 12
      }, {
        id: new Date(),
        amount3: 9
      }, {
        id: new Date(),
        amount3: 17
      }, {
        id: new Date(),
        amount3: 15
      }],
      activeIndex: '0',//初始显示菜单下标
      isShows:[
        {isShow:true},
        {isShow:false}
      ],
      queryMap: {
        pageNum: 1,
        pageSize: 10,
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      datas:[],
      datas2:[],
      dates:[],
    }
  },
  methods: {
    async getSeatsConsumeLogChange(){
      this.userId=null;
      this.getUserNickName();
      this.getSeatsConsumeLog();
    },
    async getAllAccountList(){
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if(!res.success){
        return this.$message.error("获取账号列表失败:"+res.data);
      }
      if (res.data!=null){
        this.accounts = res.data;
      }else{
        this.accounts=null
      }
    },
    handleSelect(key) {
      // this.isShows.each(key=>key=false);
      for (let i = 0; i < this.isShows.length; i++) {
        this.isShows[i].isShow=false;
      }
      this.isShows[key].isShow=true;
    },
    drawChart() {
      // 基于准备好的dom，初始化echarts实例  这个和上面的main对应
      let myChart = this.$echarts.init(this.$refs.histogram);
      // 指定图表的配置项和数据
      const option = {
        title: {
          text: '日消费汇总',
          subtext: '数据来源：每日记录',
          left: 'center',
          textStyle: {
            color: '#333',
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow', // 显示阴影效果
          },
        },
        legend: {
          data: ['消费金额', '累计消费'],
          top: '10%',
          textStyle: {
            color: '#666',
          },
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: this.dates, // 可替换为动态日期数据
          axisLine: {
            lineStyle: {
              color: '#888',
            },
          },
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '消费金额 (元)',
            position: 'left',
            axisLine: {
              lineStyle: {
                color: '#888',
              },
            },
            splitLine: {
              lineStyle: {
                type: 'dashed',
              },
            },
          },
          {
            type: 'value',
            name: '累计消费 (元)',
            position: 'right',
            axisLine: {
              lineStyle: {
                color: '#888',
              },
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: '消费金额',
            type: 'bar',
            data: this.datas, // 替换为动态数据
            itemStyle: {
              color: '#3b82f6', // 自定义柱状图颜色
            },
            barWidth: '40%',
          },
          {
            name: '累计消费',
            type: 'line',
            yAxisIndex: 1,
            data: this.datas2, // 累加动态数据
            smooth: true, // 曲线平滑
            itemStyle: {
              color: '#f97316', // 折线图颜色
            },
            lineStyle: {
              width: 2,
            },
            symbol: 'circle',
            symbolSize: 8,
          },
        ],
        dataZoom: [
          {
            type: 'inside', // 内部拖动缩放
            start: 0,
            end: 100,
          },
          {
            type: 'slider', // 底部滚动条
            start: 0,
            end: 100,
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getSysNoticeList();
    },
    async reset(){
      this.accountName='';
      this.userId=null;
      this.setDefaultDateRange();
      this.getUserNickName();
      this.getSeatsConsumeLog();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getSysNoticeList();
    },
    setDefaultDateRange() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      this.value2 = [start, end];

    },
    /**
     * 获得用户昵称信息
     */
    async getUserNickName(){
      const {data: res} = await this.$http.get("/comcentre/seats/getAllSeats",
          {params:
                {
                  accountName:this.accountName
                }
          }
      );
      if(!res.success){
        return this.$message.error("获取用户昵称信息失败:"+res.data.errorMsg);
      }
      this.userList=res.data;
    },

    convertToTargetFormat(isoDate) {
      const date = new Date(isoDate);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    convertToTargetUnTimeFormat(isoDate) {
      const date = new Date(isoDate);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    async getRechargeRecords() {
      this.tableData=[];
      this.datas = []; // 存储每次的金额
      this.datas2 = []; // 存储累加金额
      this.dates = []; // 存储时间
      let cumulativeAmount = 0; // 用于累加金额的变量

      const { data: res } = await this.$http.post("/comcentre/consumeLog/getConsumeLogs", {
        startTime: this.convertToTargetFormat(this.value2[0]),
        stopTime: this.convertToTargetFormat(this.value2[1]),
      });
      if (!res.success){
        return this.$message.error("内部错误，无法获得日消费记录");
      }
      for (let i of res.data) {
        const amount = parseFloat(i.consumptionAmount.toFixed(3)); // 当前金额
        const date = this.convertToTargetUnTimeFormat(i.endTime); // 当前时间
        this.dates.push(date); // 将时间推入 dates
        this.datas.push(amount); // 将金额推入 datas
        const data1={
          id:date,
          amount3:amount
        }
        this.tableData.push(data1);
        cumulativeAmount += amount; // 累加金额
        this.datas2.push(cumulativeAmount); // 将累加金额推入 datas2
      }
      this.drawChart(); //绘制图表
    },

    async getSeatsConsumeLog(){
      this.getUserNickName();
      const { data: res } = await this.$http.post("/comcentre/consumeLog/getSeatsConsumeLog", {
        startTime: this.convertToTargetFormat(this.value2[0]),
        stopTime: this.convertToTargetFormat(this.value2[1]),
        userId:this.userId,
        accountName:this.accountName
      });
      if (!res.success){
        return this.$message.error("内部错误，无法获得日消费记录");
      }
      this.tableData2=res.data;
      for (let i of this.tableData2) {
        i.consumptionAmount = parseFloat(i.consumptionAmount.toFixed(3)); // 当前金额
        i.endTime= this.convertToTargetUnTimeFormat(i.endTime); // 当前时间
      }
    }
  },
  created(){

  },
  mounted() {
    this.setDefaultDateRange(); // 设置默认日期范围为最近一周
    this.getRechargeRecords(); //绘制图表
    this.getAllAccountList();
    this.getSeatsConsumeLog();
    this.getUserNickName();
  },
};
</script>
<style scoped>
.el-main{
  padding: 0;
}
#showMain{
}
#showMain>div{
  width: 100%;
  height: 100%;
}
#histogram{
  width: 80%;
  height: 80%;
  margin: 2vh auto 10vh;
}
.advanced-box-shadow {
  background-color: #ffffff; /* 背景颜色 */
  box-shadow:
      0 4px 6px rgba(0, 0, 0, 0.1),  /* 主阴影 */
      0 1px 3px rgba(0, 0, 0, 0.06); /* 轻微阴影 */
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  margin: 0 3vh;
  padding:3vh 2vh;
}


</style>